/* Lab 1, exercise 8
刘文骏 2023.7.7
*/
#include <system.h>
// select switch
#define SWITCH(s) (1 << (s))
// check switch is pressed
#define CHECK_SWITCH_PRESSED(p, s) (((p) & SWITCH(s)) != 0)

//delay 125ms
void delay() {
    for (int i = 6794; i != 0; i--);
}

// left to right
void roll_ltr() {
    char tmp = 0x80;
    while (tmp != 0) {
        portb = tmp;
        tmp >>= 1;
        delay();
    }
}
// right to left
void roll_rtl() {
    char tmp = 0x01;
    while (tmp != 0) {
        portb = tmp;
        tmp <<= 1;
        delay();
    }
}

void main() {
    trisb = 0;      // set all bits in port B as outputs
    adcon1 = 0x06;  // set port A as digital inputs
    while (1) {
       if (CHECK_SWITCH_PRESSED(porta, 4)) {
            portb = porta;
        } else if (CHECK_SWITCH_PRESSED(porta, 3)) {
            roll_ltr();
            roll_rtl();
        } else if (CHECK_SWITCH_PRESSED(porta, 2)) {
            roll_ltr();
        } else if (CHECK_SWITCH_PRESSED(porta, 1)) {
            roll_rtl();
        } else if (CHECK_SWITCH_PRESSED(porta, 0)) {
            portb = 0xff;
        } else {
            portb = 0;
        }
    }
}